<?php
declare(strict_types=1);

namespace Zms\Unit;

/**
 * @describe 距离工具
 * @user zlf <zms-pro@qq.com> 2025/4/16
 */
class Distance
{
    /**
     * @describe 距离显示
     * @param float|int $distance 距离单位,单位米
     * @user zlf <zms-pro@qq.com> 2025/4/16
     * @return array{distance:float,unit:string,zh_unit:string}
     */
    public static function show($distance)
    {
        $distance = floatval($distance);
        if ($distance < 1000) {
            return ['distance' => round($distance, 2), "unit" => "m", "zh_unit" => "米"];
        }
        return ['distance' => (float)bcdiv("{$distance}", "1000", 2), "unit" => "km", "zh_unit" => "千米"];
    }


    /**
     * @describe 坐标距离计算
     * @user zlf <zms-pro@qq.com> 2025/4/16
     * @param float|string $lng1 经度1
     * @param float|string $lat1 维度1
     * @param float|string $lng2 经度2
     * @param float|string $lat2 维度2
     * @param int $precision
     * @return float
     */
    public static function calculateDistance($lng1, $lat1, $lng2, $lat2, int $precision = 10): float
    {
        $lng1 = floatval($lng1);
        $lat1 = floatval($lat1);
        $lng2 = floatval($lng2);
        $lat2 = floatval($lat2);
        // 将经纬度从度转换为弧度
        $radLat1 = deg2rad($lat1);
        $radLng1 = deg2rad($lng1);
        $radLat2 = deg2rad($lat2);
        $radLng2 = deg2rad($lng2);

        // 计算经纬度差值
        $deltaLat = $radLat2 - $radLat1;
        $deltaLng = $radLng2 - $radLng1;

        // Haversine 公式
        $a = sin($deltaLat / 2) * sin($deltaLat / 2) +
            cos($radLat1) * cos($radLat2) *
            sin($deltaLng / 2) * sin($deltaLng / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

        // 地球半径（单位：米）
        $earthRadius = 6371000;

        // 返回两点之间的距离
        return round($earthRadius * $c, $precision);
    }
}